package com.ruoyi.system.service.impl;

import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.UserBalanceLog;
import com.ruoyi.system.domain.ZhOrder;
import com.ruoyi.system.enums.PayStatus;
import com.ruoyi.system.mapper.ZhOrderMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IUserBalanceLogService;
import com.ruoyi.system.service.IZhOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单 服务层实现
 *
 * @author ruoyi
 * @date 2019-06-16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ZhOrderServiceImpl implements IZhOrderService {
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ZhOrderMapper zhOrderMapper;

    @Autowired
    private IUserBalanceLogService userBalanceLogService;

    /**
     * 查询订单信息
     *
     * @param id 订单ID
     * @return 订单信息
     */
    @Override
    public ZhOrder selectZhOrderById(Integer id) {
        return zhOrderMapper.selectZhOrderById(id);
    }

    /**
     * 查询订单列表
     *
     * @param zhOrder 订单信息
     * @return 订单集合
     */
    @Override
    public List<ZhOrder> selectZhOrderList(ZhOrder zhOrder) {
        return zhOrderMapper.selectZhOrderList(zhOrder);
    }

    /**
     * 新增订单
     *
     * @param zhOrder 订单信息
     * @return 结果
     */
    @Override
    public int insertZhOrder(ZhOrder zhOrder) {
        return zhOrderMapper.insertZhOrder(zhOrder);
    }

    /**
     * 修改订单
     *
     * @param zhOrder 订单信息
     * @return 结果
     */
    @Override
    public int updateZhOrder(ZhOrder zhOrder) {
        return zhOrderMapper.updateZhOrder(zhOrder);
    }

    /**
     * 删除订单对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteZhOrderByIds(String ids) {
        return zhOrderMapper.deleteZhOrderByIds(Convert.toStrArray(ids));
    }


    /**
     * 更新发货状态
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, readOnly = false)
    public int updateDelivery(int id) {

        finishOrder(id);

        Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now());
        return zhOrderMapper.updateDelivery(id, timestamp);
    }

    /**
     * 完结订单(将订单中的金额转入商家余额)
     *
     * @param orderId 订单id
     */
    @Transactional(rollbackFor = Exception.class, readOnly = false)
    public void finishOrder(int orderId) {
        ZhOrder zhOrder = zhOrderMapper.selectZhOrderById(orderId);

        if (zhOrder == null) {
            throw new RuntimeException("订单不存在");
        }

        // 先判断是否已发货
        if(zhOrder.getDeliveryTime()!=null){
            throw new RuntimeException("订单已发货，请勿重复操作");
        }

        if (PayStatus.UNUSUAL == zhOrder.getPayStatus()) {
            throw new RuntimeException("订单异常，无法完成发货");
        }

        if (!StringUtils.equals(String.valueOf(zhOrder.getPayStatus()), String.valueOf(PayStatus.PAIED))) {
            throw new RuntimeException("订单未付款，无法完成发货");
        }

        BigDecimal orderRealPayAmount = zhOrder.getOrderRealPayAmount();

        // 根据卖家用户名，查询用户id
        String salerUsername = zhOrder.getSalerUsername();
        SysUser sysUser = sysUserService.selectUserByLoginName(salerUsername);
        if (sysUser == null) {
            throw new RuntimeException("卖家用户名有误，无法完成发货");
        }

        // 插入余额变动日志
        UserBalanceLog userBalanceLog = new UserBalanceLog();
        userBalanceLog.setSysUserId(Math.toIntExact(sysUser.getUserId()));
        userBalanceLog.setIncreaseBalance(orderRealPayAmount);
        userBalanceLog.setOperationType(0);
        userBalanceLog.setOperationDescript("设置订单发货");
        userBalanceLog.setOutTradeNo(zhOrder.getOutTradeNo());
        userBalanceLog.setDeptId(zhOrder.getDeptId());

        userBalanceLogService.insertUserBalanceLog(userBalanceLog);

        // 增加商家余额
        sysUserService.increaseBalanceByUserId(sysUser.getUserId(), orderRealPayAmount);
    }
}
